﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace XNA_Game_Engine
{
    public class AnimatedSprite
    {
        private readonly Texture2D _sprite;
        private readonly int _timeToNextFrame;
        private readonly int _frameHeight;
        private int _timer, _frame, _frameLine, _nFramesPerLine;
        private int _frameWidth;


        public AnimatedSprite(Texture2D sprite, int timeToNextFrame, int nFramesPerLine, int nLines )
        {
            this._sprite = sprite;
            this._timeToNextFrame = timeToNextFrame;
            this._nFramesPerLine = nFramesPerLine;

            _frameLine = 0;
            _frameWidth = sprite.Width/nFramesPerLine;
            _frameHeight = sprite.Height / nLines;
        }


        public void Update(float gameTime)
        {
            _timer += (int)gameTime;

            if (_timer > _timeToNextFrame)
            {
                _frame++;
                _frame = _frame >= _nFramesPerLine ? 0 : _frame;
                _timer = 0;
            }
        }


        public void Render(SpriteBatch renderTarget, double x, double y)
        {
            Rectangle rect = new Rectangle(_frame * _frameWidth, _frameLine * _frameHeight, _frameWidth, _frameHeight);
            renderTarget.Draw(_sprite, new Vector2((float)x, (float)y), rect, Color.White);           
        }


        public void SetFrameLine( int line, int nFramesPerLine )
        {
            if (line != _frameLine)
            {
                _frameLine = line;
                this._nFramesPerLine = nFramesPerLine;
                _frameWidth = _sprite.Width / nFramesPerLine;
            }
        }


        public int GetWidth()
        {
            return _frameWidth;
        }

        public int GetHeight()
        {
            return _frameHeight;
        }


        
        } //class
} //namespace
